package com.commerce.controller.back.menu;

import com.commerce.authority.AuthType;
import com.commerce.authority.Authority;
import com.commerce.common.JsonResult;
import com.commerce.model.Menu;
import com.commerce.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wyj
 * @Title:菜单控制器
 * @Description:菜单控制器
 */
@Controller
@RequestMapping(value = "/admin/menu" , method = RequestMethod.POST)
public class MenuController {

    @Autowired
    private MenuService menuService;

    /**
     * 列表页面
     * @return String
     */
    @RequestMapping(value = "list")
    @Authority(AuthType.MENU_SELECT)
    public String list(){
        return "back/menu/list";
    }

    /**
     * 列表查询
     * @return JsonResult
     */
    @ResponseBody
    @RequestMapping(value = "pageList")
    public JsonResult pageList(){
        List<Menu> list = menuService.selectList();
        List<Menu> menus = new ArrayList<>();
        for(Menu menu :list){
            menus.add(menu);
            if(menu.getSeed()==null){
                continue;
            }
            for(Menu m : menu.getSeed()){
                menus.add(m);
            }
        }
        return JsonResult.returnJsonResult("0","","0",menus);
    }

    /**
     *新增或修改页面
     * @return String
     */
    @RequestMapping("/info")
    @Authority({AuthType.MENU_INSERT,AuthType.MENU_UPDATE})
    public String info(Integer id , Model model){
        Menu menu = null;
        if(id != null){
            menu = menuService.selectById(id);
        }
        model.addAttribute("menu",menu);
        model.addAttribute("menuList",menuService.selectMainMenu());
        return "back/menu/info";
    }

    /**
     * 新增
     * @param menu
     * @param request
     * @return String
     */
    @ResponseBody
    @RequestMapping("/addMenu")
    @Authority(AuthType.MENU_INSERT)
    public String addMenu(Menu menu , HttpServletRequest request){
        return menuService.insert(menu,request);
    }

    /**
     * 修改菜单
     * @param menu
     * @param request
     * @return String
     */
    @ResponseBody
    @RequestMapping("/editMenu")
    @Authority(AuthType.MENU_UPDATE)
    public String editMenu(Menu menu, HttpServletRequest request){
        return menuService.update(menu,request);
    }

    /**
     * 删除菜单
     * @param id
     * @return String
     */
    @ResponseBody
    @RequestMapping("/delMenu")
    @Authority(AuthType.MENU_DELETE)
    public String delById(int id){
        return menuService.deleteById(id);
    }
}
